import React from 'react';
import { Button, Form, Input } from 'antd';
import { LockOutlined, UserOutlined } from '@ant-design/icons';

class RenewDept extends React.Component {
  constructor(props) {
    super(props);
    console.log("constructor");
    this.formRef = React.createRef();
  }

  onFinish = (values) => {
    const { currentDept, refresh, closeDrawer } = this.props;
    const url = currentDept ? `http://1.94.134.166:8805/dept/${currentDept.deptId}` : "http://1.94.134.166:8805/dept";
    const method = currentDept ? 'PUT' : 'POST';

    fetch(url, {
      method,
      body: JSON.stringify(values),
      headers: {
        'Content-type': 'application/json',
        Authorization: localStorage.getItem('Authorization'),
      },
    })
      .then((response) => response.json())
      .then((res) => {
        const { code = 0 } = res;
        if (code === 0) {
          refresh();
          closeDrawer();
          this.formRef.current.resetFields();
        }
      });
  };

  render() {
    const { currentDept } = this.props;
    return (
      <Form
        name="dept_form"
        className="dept-form"
        onFinish={this.onFinish}
        ref={this.formRef}
        initialValues={currentDept || {}}
      >
        <Form.Item
          name="deptName"
          label="部门名称"
          rules={[
            {
              required: true,
              message: '请输入部门名称!',
            },
            {
              pattern: /^[A-Za-z\u4e00-\u9fa5]+$/,
              message: '部门名称只允许中文和英文!',
            },
          ]}
        >
          <Input size="large" placeholder="请输入部门名称!" />
        </Form.Item>

        <Form.Item
          name="deptPy"
          label="部门拼音"
          rules={[
            {
              required: true,
              message: '请输入部门拼音!',
            },
            {
              pattern: /^[A-Za-z]+$/,
              message: '部门拼音只允许字母!',
            },
          ]}
        >
          <Input size="large" placeholder="请输入部门拼音!" />
        </Form.Item>

        <Form.Item
          name="phone"
          label="联系人电话"
          rules={[
            {
              required: true,
              message: '请输入联系人电话!',
            },
            {
              pattern: /^1[3-9]\d{9}$/,
              message: '请输入正确的手机号码!',
            },
          ]}
        >
          <Input size="large" placeholder="请输入联系人电话!" />
        </Form.Item>

        <Form.Item>
          <div style={{ margin: '0 auto' }}>
            <Button type="primary" htmlType="submit">
              {currentDept ? '修改' : '添加'} 部门
            </Button>
          </div>
        </Form.Item>
      </Form>
    );
  }
}

export default RenewDept;
